package com.personal.test.controller.download;
import com.personal.test.common.exception.MyFileNotFoundException;
import com.personal.test.common.exception.MyUnsupportedEncodingException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author linyh
 * @email 1503386669@qq.com
 * @date 2020/10/19 14:55
 * @version 1.0
 */

/**
 * 文件下载类
 */
@Controller
public class DownloadController {

    /**
     * 下载指定文件路径的文件
     * @param filePath  文件路径
     * @param response
     */
    @PostMapping("/download")
    public void downloadFile(String filePath, HttpServletResponse response, HttpServletRequest request){
        File file = new File(filePath);
        // 取得文件名。
        String fileName = file.getName();
        InputStream fis = null;
        try {
            try {
                fis = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                throw new MyFileNotFoundException("文件未找到");
            }
            try {
                request.setCharacterEncoding("UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new MyUnsupportedEncodingException("格式错误");
            }
            String agent = request.getHeader("User-Agent").toUpperCase();
            if ((agent.indexOf("MSIE") > 0) || ((agent.indexOf("RV") != -1) && (agent.indexOf("FIREFOX") == -1))) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes("UTF-8"), "UTF-8");
            }
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setHeader("Content-Length", String.valueOf(file.length()));
            byte[] b = new byte[1024];
            int len;
            while ((len = fis.read(b)) != -1) {
                response.getOutputStream().write(b, 0, len);
            }
            response.flushBuffer();
            fis.close();
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
